package com.lixin.yun_notebook;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import bean.Note;
import bean._User;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListListener;

import com.google.gson.Gson;
import com.lixin.yun_notebook.adapter.NoteAdapter;

public class MainActivity extends FragmentActivity implements
	OnItemClickListener {
	_User user;
	ListView noteListView;
	ImageButton add_btn;
	NoteAdapter adapter;
	List<Note> noteList;
	ImageButton loginBtn;
	ImageButton deleteBtn;
	ImageButton backBtn;
	TextView countNote;
	ViewSwitcher searchSwitcher;
	ViewSwitcher deleteSwitcher;
	SharedPreferences sp;
	String authorId;
	static final int REQ_CODE_EDIT = 99;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Bmob.initialize(this, "fd0095ad6d79af2484a64282419415fa");
		initView();

	}

	private void initView() {
		sp = this.getSharedPreferences("userInfo", MODE_PRIVATE);
		authorId = sp.getString("authorId", "");
		searchSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher1);
		deleteSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher2);
		noteListView = (ListView) findViewById(R.id.listview);
		noteList = new ArrayList<Note>();
		adapter = new NoteAdapter(this, noteList);
		noteListView.setAdapter(adapter);
		reflashList();
		noteListView.setOnItemClickListener(this);

		loginBtn = (ImageButton) findViewById(R.id.login);
		loginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (sp.getBoolean("isLogin", false)) {
					Intent intent = new Intent(MainActivity.this,
							UserCenterActivity.class);
					startActivity(intent);
					finish();
				} else {
					Intent intent = new Intent(MainActivity.this,
							LoginActivity.class);
					startActivity(intent);
					finish();
				}

			}
		});

		add_btn = (ImageButton) findViewById(R.id.add_btn);
		add_btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				startActivityForResult(new Intent(getApplicationContext(),
						EditActivity.class), REQ_CODE_EDIT);
			}
		});

	}

	private void reflashList() {
		noteList.clear();
		BmobQuery<Note> query = new BmobQuery<Note>();
		// 查询已登录作者的日记
		// 根据用户名查找对应的日记
		query.addWhereEqualTo("authorId", authorId);
		query.order("-createdAt");
		query.findObjects(new FindListener<Note>() {
			@Override
			public void done(List<Note> object, BmobException e) {
				if (e == null) {
					countNote = (TextView) findViewById(R.id.countNote);
					countNote.setText(object.size() + "条记录");
					noteList.addAll(object);
					if (noteList.isEmpty()) {
						noteListView
								.setEmptyView(findViewById(R.id.layout_empty));
					} else {
						adapter.notifyDataSetChanged();
					}
				} else {
					noteListView.setEmptyView(findViewById(R.id.layout_empty));
					Toast.makeText(MainActivity.this, "获取失败",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	// 搜索框切换
	public void searchSwitcher(View v) {
		if (v.getId() == R.id.action_search) {
			searchSwitcher.setDisplayedChild(1);
		}
		if (v.getId() == R.id.action_cancel) {
			searchSwitcher.setDisplayedChild(0);
			// word.setText("");
			reflashList();
		}
	}

	public void deleteSwitcher(View v) {
		if (v.getId() == R.id.delete_btn) {
			adapter.flage = true;
			deleteSwitcher.setDisplayedChild(1);
			adapter.notifyDataSetChanged();
		}
		if (v.getId() == R.id.back) {
			adapter.flage = false;
			deleteSwitcher.setDisplayedChild(0);
			reflashList();
			adapter.notifyDataSetChanged();
		}
	}

	public void btnSelectAllList(View view) {
		if (adapter.flage) {
			for (int i = 0; i < noteList.size(); i++) {
				noteList.get(i).setIsCheck(true);
			}
			adapter.notifyDataSetChanged();
		}
	}

	public void btnNoList(View view) {

		if (adapter.flage) {
			for (int i = 0; i < noteList.size(); i++) {
				noteList.get(i).setIsCheck(false);
			}

			adapter.notifyDataSetChanged();
		}
	}

	public void btnfanxuanList(View view) {
		if (adapter.flage) {
			for (int i = 0; i < noteList.size(); i++) {
				if (noteList.get(i).getIsCheck()) {
					noteList.get(i).setIsCheck(false);
				} else {
					noteList.get(i).setIsCheck(true);
				}
			}

			adapter.notifyDataSetChanged();
		}
	}

	public void btnOperateList(View view) {

		List<BmobObject> Notes = new ArrayList<BmobObject>();

		if (adapter.flage) {

			for (int i = 0; i < noteList.size(); i++) {
				Note temp = noteList.get(i);
				if (temp.getIsCheck()) {
					Notes.add(temp);
				}
			}

			// Toast.makeText(MainActivity.this,ids.toString(),
			// Toast.LENGTH_SHORT).show();
		}
		new BmobBatch().deleteBatch(Notes).doBatch(
				new QueryListListener<BatchResult>() {

					@Override
					public void done(List<BatchResult> o, BmobException e) {
						if (e == null) {
							for (int i = 0; i < o.size(); i++) {
								BatchResult result = o.get(i);
								BmobException ex = result.getError();
								if (ex == null) {
									reflashList();
									adapter.notifyDataSetChanged();
								} else {
									adapter.notifyDataSetChanged();
									Toast.makeText(
											MainActivity.this,
											"第" + i + "个数据批量删除失败："
													+ ex.getMessage() + ","
													+ ex.getErrorCode(),
											Toast.LENGTH_SHORT).show();
								}
							}
						} else {
							Toast.makeText(MainActivity.this,
									"删除失败：" + e.getMessage(),
									Toast.LENGTH_SHORT).show();
						}
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent it = new Intent(MainActivity.this, EditActivity.class);
		it.putExtra("objStr", new Gson().toJson(noteList.get(arg2)));
		startActivityForResult(it, REQ_CODE_EDIT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		reflashList();
	}
}
